<template>
  <div class="app-container">
    <upload-excel-component
      :on-success="handleSuccess"
      :before-upload="beforeUpload"
    />
  </div>
</template>

<script>
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
import { formatExcelDate } from '@/utils/index'
import { importEmployee } from '@/api/employees'
export default {
  name: 'UploadExcel',
  components: { UploadExcelComponent },
  data() {
    return {
      tableData: [],
      tableHeader: []
    }
  },
  methods: {
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1
      if (isLt1M) {
        return true
      }
      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },

    async handleSuccess({ results, header }) {
      console.log('读出来的excel的内容是', results, header)

      try {
        this.tableData = results
        this.tableHeader = header

        const newData = this.himport(results, header)
        console.log(newData)
        const res = await importEmployee(newData)
        this.$message.success(res.message)
        this.$router.push('/employees')
      } catch (error) {
        this.$message.success(error)
      }
    },
    himport(results, header) {
      const mapInfo = {
        入职日期: 'timeOfEntry',
        手机号: 'mobile',
        姓名: 'username',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        部门: 'departmentName',
        聘用形式: 'formOfEmployment'
      }
      return results.map((item) => {
        const obj = {}
        header.forEach((zhKey) => {
          const enKey = mapInfo[zhKey]
          if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
            obj[enKey] = new Date(formatExcelDate(item[zhKey]))
          } else {
            obj[enKey] = item[zhKey]
          }
        })
        return obj
      })
    }
  }
}
</script>
